#ifndef __MY_DATA_MANAGER__
#define __MY_DATA_MANAGER__

#include <iostream>
#include <unordered_map>
#include <string>
#include <pthread.h>
#include <vector>
#include <jsoncpp/json/json.h>
#include "Util.hpp"
#include "Config.hpp"

namespace cloud
{
    typedef struct BackupInfo_t
    {
        bool pack_flag;        // 该备份文件是否压缩的标志
        size_t fsize;          // 文件大小
        time_t atime;          // 最后一次访问时间
        time_t mtime;          // 最后一次修改时间
        std::string real_path; // 文件实际存储路径名称
        std::string pack_path; // 压缩包存储路径名称
        std::string url_path;

        bool NewBackupInfo(std::string &realpath, BackupInfo_t *info)
        {
            FileUtil fu(realpath);
            if (fu.Exists() == false)
            {
                std::cout << "new BackupInfo file is not exist" << std::endl;
                return false;
            }
            std::string filename = fu.FileName();
            Config *config = Config::GetInstance();
            std::string suffix = config->GetPackfileSuffix();
            std::string packdir = config->GetPackDir();
            std::string download_prefix = config->GetDownloadPrefix();
            pack_flag = false;
            fsize = fu.FileSize();
            atime = fu.LastATime();
            mtime = fu.LastMTime();
            real_path = realpath;
            // ./a.txt --> ./packdir/a.txt.lz
            pack_path = packdir + filename + suffix;
            url_path = download_prefix + filename;
            return true;
        }
    } BackupInfo;

    class DataManager
    {
    private:
        std::string _backup_file;
        pthread_rwlock_t _rwlock;
        std::unordered_map<std::string, BackupInfo> _hash;

    public:
        DataManager()
        {
            _backup_file = Config::GetInstance()->GetBackupFile();
            pthread_rwlock_init(&_rwlock, NULL); // 初始化读写锁
            InitLoad();
        }
        ~DataManager()
        {
            pthread_rwlock_destroy(&_rwlock);
        }
        bool Insert(const BackupInfo &info)
        {
            pthread_rwlock_wrlock(&_rwlock);
            _hash[info.url_path] = info;
            pthread_rwlock_unlock(&_rwlock);
            Storage();
            return true;
        }
        bool Update(const BackupInfo &info)
        {
            pthread_rwlock_wrlock(&_rwlock);
            _hash[info.url_path] = info;
            pthread_rwlock_unlock(&_rwlock);
            Storage();
            return true;
        }
        bool GetOneByURL(const std::string &url, BackupInfo *info)
        {
            pthread_rwlock_wrlock(&_rwlock);
            auto it = _hash.find(url);
            if (it == _hash.end())
            {
                pthread_rwlock_unlock(&_rwlock);
                return false;
            }
            *info = it->second;
            pthread_rwlock_unlock(&_rwlock);
            return true;
        }
        bool GetOneByRealPath(const std::string &realpath, BackupInfo *info)
        {
            pthread_rwlock_wrlock(&_rwlock);
            auto it = _hash.begin();
            for (; it != _hash.end(); ++it)
            {
                if (realpath == it->second.real_path)
                {
                    *info = it->second;
                    pthread_rwlock_unlock(&_rwlock);
                    return true;
                }
            }
            pthread_rwlock_unlock(&_rwlock);
            return false;
        }
        bool GetAll(std::vector<BackupInfo> *array)
        {
            pthread_rwlock_wrlock(&_rwlock);
            auto it = _hash.begin();
            for (; it != _hash.end(); ++it)
            {
                array->push_back(it->second);
            }
            pthread_rwlock_unlock(&_rwlock);
            return true;
        }
        bool Storage()
        {
            std::vector<BackupInfo> array;
            GetAll(&array);
            Json::Value root;
            for(auto& a : array)
            {
                Json::Value item;
                item["pack_flag"] = a.pack_flag;
                item["fsize"] = a.fsize;
                item["atime"] = a.atime;
                item["mtime"] = a.mtime;
                item["real_path"] = a.real_path;
                item["pack_path"] = a.pack_path;
                item["url_path"] = a.url_path;
                root.append(item);
            }
            std::string body;
            JsonUtil::Serialize(root, &body);
            FileUtil fu(_backup_file);
            fu.SetContent(body);
            return true;
        }
        bool InitLoad()
        {
            //1.读取文件内容
            FileUtil fu(_backup_file);
            if(fu.Exists() == false)
            {
                return true;
            }
            std::string body;
            fu.GetContent(&body);
            //如果文件里面没有内容，就直接返回，如果继续执行后面就会报错
            if(body.size() == 0)  
            {
                return true;
            }

            //2.反序列化
            Json::Value root;
            JsonUtil::UnSerialize(body, &root);
            //3.写入哈希表中(加载到内存)
            for(int i = 0; i < root.size(); i++)
            {
                BackupInfo info;
                info.pack_flag = root[i]["pack_flag"].asBool();
                info.fsize = root[i]["fsize"].asInt64();
                info.atime = root[i]["atime"].asInt64();
                info.mtime = root[i]["mtime"].asInt64();
                info.real_path = root[i]["real_path"].asString();
                info.pack_path = root[i]["pack_path"].asString();
                info.url_path = root[i]["url_path"].asString();
                _hash[info.url_path] = info;
            }
            return true;
        }
    };
}
#endif